package org.csu.mybigpro.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.csu.mybigpro.DTO.*;
import org.csu.mybigpro.aspect.ApiOperationLog;
import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.service.ForumService;
import org.csu.mybigpro.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/threads")
public class ForumController {

    @Autowired
    private ForumService forumservice;

    @Autowired
    @Qualifier("InRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private MinioUtil minioUtil;

    @GetMapping
    @ApiOperationLog(description = "分页获取帖子")
    public CommonResponse<GetThreadsRspVO> getThreads(@Validated GetThreadsReqVO reqVO) { // <-- 看这里，@RequestBody 已经被移除了
        return forumservice.getThreads(reqVO);
    }

    @GetMapping("/{threadId}")
    @ApiOperationLog(description = "获取单个帖子的详细信息及其回帖列表（分页）")
    public CommonResponse<GetThreadByIdRspVO> getThreadsById(@Validated GetThreadByIdReqVO reqVO, @PathVariable int threadId) { // @RequestBody 已移除
        reqVO.setThreadId((long) threadId);
        return forumservice.getThreadsById(reqVO);
    }

    @PostMapping
    @ApiOperationLog(description = "创建一个新的帖子主题")
    public CommonResponse<CreateThreadRspVO> createThread(@RequestBody @Validated CreateThreadReqVO reqVO, HttpServletRequest request){
        String teacherId = GetUserIdByToken(request);
        return forumservice.createThread(teacherId,reqVO);
    }


    @PutMapping("/{threadId}/read")
    @ApiOperationLog(description = "增加帖子的阅读量+1")
    public CommonResponse<AddReadRspVO> addRead(@RequestBody @Validated AddReadReqVO reqVO, @PathVariable int threadId, HttpServletRequest request) {
        reqVO.setThreadId(threadId);
        String teacherId = GetUserIdByToken(request);
        return forumservice.addRead(teacherId,reqVO);
    }


    @PostMapping("/{threadId}/replies")
    @ApiOperationLog(description = "在一个帖子下创建新的回帖")
    public CommonResponse<CreateReplyRspVO> createReply(@RequestBody @Validated CreateReplyReqVO reqVO, @PathVariable int threadId, HttpServletRequest request){
        String teacherId = GetUserIdByToken(request);
        reqVO.setThreadId((long) threadId);
        return forumservice.createReply(teacherId,reqVO);
    }

    @PutMapping("/replies/{repliesId}/thumbsup")
    @ApiOperationLog(description = "点赞+1")
    public CommonResponse<ThumbsUpRspVO> thumbsUp(@RequestBody @Validated ThumbsUpReqVO reqVO, @PathVariable int repliesId, HttpServletRequest request) {
        String teacherId = GetUserIdByToken(request);
        reqVO.setReplyId(repliesId);
        return forumservice.thumbsUp(teacherId, reqVO);
    }

    @PutMapping("/replies/{repliesId}/thumbsdown")
    @ApiOperationLog(description = "点赞-1")
    public CommonResponse<ThumbsDownRspVO> thumbsDown(@RequestBody @Validated ThumbsDownReqVO reqVO, @PathVariable int repliesId, HttpServletRequest request) {
        String teacherId = GetUserIdByToken(request);
        reqVO.setReplyId(repliesId);
        return forumservice.thumbsDown(teacherId,reqVO);
    }

    @DeleteMapping("/replies/{repliesId}")
    @ApiOperationLog(description = "删除回帖，仅帖子创建者和回帖发布者可以删除")
    public CommonResponse<DelReplyRspVO> DelReply(@RequestBody @Validated DelReplyReqVO reqVO, @PathVariable int repliesId, HttpServletRequest request) {
        String teacherId = GetUserIdByToken(request);
        reqVO.setReplyId(repliesId);
        return forumservice.DelReply(teacherId,reqVO);
    }

    @PostMapping("/image")
    @ApiOperationLog(description = "上传图片")
    public CommonResponse<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file){
        try {
            String url = minioUtil.uploadFile(file);
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            // 返回一个包含图片URL的对象，方便前端解析
            return CommonResponse.createForSuccess(data);
        } catch (Exception e) {
            // 建议创建更具体的异常处理
            return CommonResponse.createForError(500, "文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/file") // 建议使用 /api/threads/file 路径
    @ApiOperationLog(description = "上传通用文件")
    public CommonResponse<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResponse.createForError(400, "上传的文件不能为空");
        }
        try {
            String url = minioUtil.uploadFile(file); // 假设你的minio工具类能处理各种文件
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            data.put("fileName", file.getOriginalFilename()); // 返回原始文件名
            data.put("fileType", file.getContentType() != null ? file.getContentType() : MediaType.APPLICATION_OCTET_STREAM_VALUE); // 返回文件的MIME类型

            return CommonResponse.createForSuccess(data);
        } catch (Exception e) {
            // Log the exception
            return CommonResponse.createForError(500, "文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 一个调用Token接口的工具
     * @param request
     * @return
     */
    public String GetUserIdByToken(HttpServletRequest request){
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headers.set(headerName, request.getHeader(headerName));
        }
        // 2. 调用接口
        HttpEntity<Void> entity = new HttpEntity<>(headers);
        String url = "http://localhost:8080/api/teacher/profile";
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);
        // 3. 提取 data.id
        String teacherId = null;
        if (response.getStatusCode().is2xxSuccessful()) {
            Map<String, Object> body = response.getBody();
            if (body != null && body.get("data") instanceof Map) {
                Map data = (Map) body.get("data");
                teacherId = (String) data.get("id");
            }
        }
        return teacherId;

    }
}
